package ia.util;

import ia.auxiliar.NXTConnector;

import java.io.IOException;

import lejos.nxt.remote.NXTCommand;
import lejos.pc.comm.NXTComm;
import lejos.pc.comm.NXTCommFactory;
import lejos.pc.comm.NXTCommLogListener;
/**
 * Clase para facilitar la conexion por bluetooth/USB
 * 
 * @author Armando Andini
 *
 */
public class Connector {
	static NXTConnector connector = null;
	static NXTCommLogListener logger = null;
	
	public static boolean connectUSB(){
		log("Creando conector");
		connector = new NXTConnector();
		if(logger != null)
			connector.addLogListener(logger);
		log("Intentando conectar por USB.. toma su tiempo");
		boolean res = connector.connectTo("", "", NXTCommFactory.USB);
		if(res){
			log("Conexion exitosa");
			NXTCommand.getSingleton().setNXTComm(connector.getNXTComm());
			return true;
		}
		else{
			log("No se pudo conectar");
			return false;
		}
	}
	
	public static boolean connectBT(){
		log("Creando conector");
		connector = new NXTConnector();
		connector.setDebug(true);
		if(logger != null)
			connector.addLogListener(logger);
		log("Intentando conectar por bluetooth.. toma su tiempo");
		boolean res = connector.connectTo(null, null, NXTCommFactory.BLUETOOTH,NXTComm.PACKET);
		if(res){
			log("Conexion exitosa");
			NXTCommand.getSingleton().setNXTComm(connector.getNXTComm());
			return true;
		}
		else{
			log("No se pudo conectar");
			return false;
		}
	}
	
	public static void disconnect() throws IOException{
		if(connector != null){
			log("Cerrando conector existente");
			connector.close();
			connector = null;
		}
		else{
			log("Se llamo a desconectar pero no existe un conector");
		}
	}
	
	public static void setLogger(NXTCommLogListener aLogger){
		logger = aLogger;
	}
	
	public static void log(String msg){
		if(logger != null)
			logger.logEvent(msg);
	}
	
}
